//
//  CZRefreshControl.swift
//  仿写微博
//
//  Created by tuimao on 2017/8/3.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit

enum CZRefreshState {
    case Normal
    case Pulling
    case WillRefresh
}

class CZRefreshControl: UIControl {
    //弱引用父视图控件
    weak var scrollView:UIScrollView?
    //懒加载控件view
    lazy var refresView:CZRefreshView = CZRefreshView.refreshView()
    //临界点
    var CZRefreshOffset:CGFloat = 0
    var height:CGFloat = 0
    
     init() {
        super.init(frame: CGRect())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //在父控制器将要变化
    ///
    /// - Parameter newSuperview: 父控制器
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        //判断是否是带有UIScrollView的控制器
        guard let v = newSuperview as? UIScrollView else {
            return
        }
        //守护传值
        scrollView = v
        //临界点赋值
         CZRefreshOffset = subviews[0].frame.height
        //给父控制器设置KVO观察者
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
    }
    //
    /// 观察者的方法
    ///
    /// - Parameters:
    ///   - keyPath: 路径
    ///   - object: 哪个对象调用
    ///   - change: 改变的哪个值
    ///   - context: 上下文
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let sv = scrollView else {
            return
        }
        //高度
        height = -((sv.contentInset.top)  + (sv.contentOffset.y))
        //如果高度小于0，代表向上滑动，那么不显示
        if height < 0{
            return
        }
        //设置控制器本身高度
        self.frame = CGRect(x: 0, y: -height, width: UIScreen.main.bounds.width, height: height)
        //传递父视图高度
        if refresView.refreshState != .WillRefresh{
         refresView.parentViewHeight = height   
        }
        //判断下拉状态
        if sv.isDragging {
            //如果高度超出临界下拉高度，而且刷新视图状态是Normal
            if  height > CZRefreshOffset && refresView.refreshState == .Normal{
                //更改刷新状态
                refresView.refreshState = .Pulling
                print("松手刷新....")
            }else if height <= CZRefreshOffset && refresView.refreshState == .Pulling  {
                print("正在使劲....")
                refresView.refreshState = .Normal
            }
        }else{
            if refresView.refreshState == .Pulling {
                print("准备开始刷新")
                //发送valueChanged的通知
                sendActions(for: .valueChanged)
                //结束刷新之后吧状态改为.Normal
                beginRefreshing()
            }
        }
    }
    //在离开父视图之前注销通知
    override func removeFromSuperview() {
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        super.removeFromSuperview()
        
    }
    
    /// 开始刷新
    func beginRefreshing(){
        print("开始刷新")
        guard let sv = scrollView else { return
        
        }
        //网络情况不好时候，多次进入下拉刷新的判断，如果已经进入状态等待即可
        if refresView.refreshState == .WillRefresh {
            return
        }
        //改变缩进，展示下拉状态
        refresView.refreshState = .WillRefresh
        var inset = sv.contentInset
        inset.top += CZRefreshOffset
        sv.contentInset = inset
        //更新父视图高度
        refresView.parentViewHeight = CZRefreshOffset
        
    }
    /// 结束刷新
    func endRefreshing(){
        guard let sv = scrollView else { return
            
        }
        //防止多次的调用下拉结束刷新，造成间距变化
        if refresView.refreshState != .WillRefresh {
            return
        }
        //更改状态
        refresView.refreshState = .Normal
        //改变缩进，恢复状态
        var inset = sv.contentInset
        inset.top -= CZRefreshOffset
        sv.contentInset = inset
        print("结束刷新")
    }
}

extension CZRefreshControl{
    fileprivate func setupUI(){
        //背景颜色
        backgroundColor = superview?.backgroundColor
        //减去超出视图的
//        clipsToBounds = true
        addSubview(refresView)
        //使用autolayout关闭
        refresView.translatesAutoresizingMaskIntoConstraints = false
        //布局xib
        addConstraint(NSLayoutConstraint(item: refresView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refresView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refresView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refresView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refresView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refresView.bounds.height))
    }
    
    
}
